package thread;

import java.util.Random;

public class Test15_synchronized {
    public static void main(String[] args) {
        SellTickOp sto = new SellTickOp(10);
        for (int i=0 ;i<12;i++){
            Thread counter1 = new Thread(sto,"柜员-----"+i);
            counter1.start();
        }
    }
}
//synchronized 同步
//卖票的任务
class SellTickOp implements Runnable{
    int tickets;//总票数
    Random r = new Random();

    public SellTickOp(int tickets){
        this.tickets = tickets;
    }
    @Override
    public void run() {
        while (true){
            synchronized (this){
                if (tickets>0){//块级同步 两种同步：方法级 synchronized void 方法名(){}
                    //块级：将同步加到要同步的代码上，注意synchronized(参照对象){}
                    System.out.println(Thread.currentThread().getName()+"在卖第"+(tickets--)+"张票");
                    try {
                        //模拟出票时间
                        Thread.sleep(1);
                        //wait(r.nextInt(100));//必须与synchronized结合使用
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    return;
                }
            }
        }
    }
}
